<template>
  <view class="wrapper">
    <view class="content">
      <view class="con_a">
        <view v-for="(item, index) in addressList" :key="index">
          <view class="consignee" @click="handleList(item)">
            <view class="cge_a"> 收货人：{{ item.name }} </view>
            <view class="cge_b">{{ item.mobile }}</view>
          </view>
          <view class="address"> 收货地址：{{ item.ap + item.ac + item.ad + item.as }} </view>
          <view class="operation">
            <view class="oper_a">
              <image
                @click="handleDefault(item)"
                :src="item.default ? '/src/static/images/xz2.png' : '/src/static/images/xz1.png'"
              />
              <view>设为默认地址</view>
            </view>
            <view class="oper_b">
              <view class="sub_a" @click="upadteAddress(item)">编辑</view>
              <view class="sub_a" @click="deleteAddress(item)">删除</view>
            </view>
          </view>
        </view>
      </view>
      <Empty :top="'220px'" v-if="addressList.length == 0" />
      <view class="added" @click="navigateTo('/pages/add-address/index')">添加新地址</view>
    </view>
  </view>
</template>
<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app';
  import { ref } from 'vue';
  import {
    getProvinceApi,
    getAddressApi,
    getCityApi,
    getDistrictApi,
    getStreetApi,
    deleteAddressApi,
    orderPickupApi,
    setDefaultAddressApi,
  } from '@/api/index';

  const orderInfo = ref<any>({});
  const addressList = ref([]) as any;
  function navigateTo(url) {
    uni.navigateTo({
      url,
    });
  }
  function upadteAddress(item) {
    const objString = JSON.stringify(item);
    uni.navigateTo({
      url: `/pages/add-address/index?item=${encodeURIComponent(objString)}`,
    });
  }
  function deleteAddress(item) {
    deleteAddressApi({ id: item.id })
      .then(() => {
        uni.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000,
        });
        Load();
      })
      .catch(() => {});
  }
  function handleList(item) {
    if (orderInfo.value) {
      orderPickupApi({ order_id: orderInfo.value.id, address_id: item.id }).then((res) => {
        uni.showToast({
          title: `${res.msg}`,
          icon: 'none',
          duration: 2000,
        });
        let obj = {
          ac_name: item.ac,
          ad_name: item.ad,
          ap_name: item.ap,
          as_name: item.as,
          address: '',
          create_time: item.create_time,
          mobile: item.mobile,
          gift_name: item.name,
          is_send: 0,
          prize: {
            ...orderInfo.value.prize,
          },
        };
        const objSteing = JSON.stringify(obj);

        uni.navigateTo({
          url: `/pages/orderData/index?item=${encodeURIComponent(objSteing)}`,
        });
      });
    }
  }
  function handleDefault(item) {
    setDefaultAddressApi({ id: item.id }).then((res) => {
      addressList.value.forEach((item) => {
        item.default = false;
      });
      item.default = true;
      uni.showToast({
        title: `${res.msg}`,
        icon: 'success',
        duration: 2000,
      });
    });
  }
  async function processIds(arr) {
    const result = [] as any;
    for (const item of arr) {
      const getProvince = await getProvinceApi();
      const province = getProvince.find((province) => province.id === item.ap_id)?.name;
      const getCity = await getCityApi({ parent_id: item.ap_id });
      const city = getCity.find((city) => city.id === item.ac_id)?.name;

      const getDistrict = await getDistrictApi({ parent_id: item.ac_id });
      const district = getDistrict.find((district) => district.id === item.ad_id)?.name;

      const getStreet = await getStreetApi({ parent_id: item.ad_id });
      const street = getStreet.find((street) => street.id === item.as_id)?.name;
      result.push({
        ...item,
        ap: province,
        ac: city,
        ad: district,
        as: street,
      });
    }
    return result;
  }

  async function Load() {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });

    try {
      const getAddress = await getAddressApi();
      addressList.value = await processIds(getAddress.list);
    } catch (error) {
      console.error(error);
    } finally {
      uni.hideLoading();
    }
  }

  onLoad(async (query) => {
    if (query?.item) {
      const objString = decodeURIComponent(query?.item);
      const item = JSON.parse(objString);
      orderInfo.value = item;
    }

    Load();
  });
</script>
<style lang="scss" scoped>
  .wrapper {
    min-height: 100%;
    overflow-y: auto;
    background-color: #f4f5f7;
    padding-bottom: 20px;

    .content {
      padding: 0 4%;

      .con_a {
        background: #fff;
        border-radius: 3px;
        padding: 0 10px;
        margin-top: 10px;

        view {
          .consignee {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            padding: 12px 0;

            .cge_a {
              font-size: 14px;
              color: #323232;
            }

            .cge_b {
              margin-left: 24px;
              font-size: 14px;
              color: #323232;
            }
          }

          .address {
            padding-bottom: 14px;
            font-size: 14px;
            color: #323232;
            border-bottom: 1px solid #eee;
          }

          .operation {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 54px;

            .oper_a {
              display: flex;
              justify-content: flex-start;
              align-items: center;

              image {
                width: 15px;
                height: 15px;
              }

              view {
                margin-left: 6px;
                font-size: 14px;
                color: #323232;
              }
            }

            .oper_b {
              display: flex;
              justify-content: flex-end;
              align-items: center;

              .sub_a {
                width: 48px;
                height: 23px;
                border: 1px solid #999;
                text-align: center;
                line-height: 23px;
                font-size: 14px;
                color: #999;
                margin-left: 10px;
              }
            }
          }
        }
      }

      .added {
        margin-top: 50px;
        width: 100%;
        height: 45px;
        background: linear-gradient(270deg, #ff8361, #ff5525);
        border-radius: 23px;
        text-align: center;
        line-height: 45px;
        font-size: 15px;
        font-weight: 600;
        color: #fff;
      }
    }
  }
</style>
